import { Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { Response } from "express";
import { System } from "src/system/system.entity";
import { UserService } from "src/user/user.service";
import { UserSys } from "src/user/userSys.entity";
import { tokenMaxAge } from "src/util/config";
import { cryptoPassword } from "src/util/crypto";


@Injectable()
export class AuthService {
    constructor(
        private readonly jwtService: JwtService,
        private readonly userService: UserService
    ) { }

    public setToken(res: Response, token: string) {
        res.cookie("token", token, {
            expires: new Date(Date.now() + tokenMaxAge),
            httpOnly: false,
            path: "/"
        })
        res.send(token);
    }

    public async signToken(
        userSys: UserSys,
        allow: string,
        system: System = userSys.system
    ) {
        const crypto = cryptoPassword(userSys.password)
        await this.userService.userSys.update({ id: userSys.id }, {
            login_ip: allow
        })
        return this.jwtService.sign({
            crypto,
            allow,
            type: "signed",
            id: userSys.id,
            system: system?.id
        })
    }
}